import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { SalesStats } from '../../types';

interface SalesState {
  overview: {
    totalRevenue: number;
    totalOrders: number;
    totalProducts: number;
    totalCustomers: number;
    averageOrderValue: number;
    conversionRate: number;
  };
  trends: {
    revenueData: Array<{
      date: string;
      revenue: number;
      orders: number;
    }>;
    categoryData: Array<{
      category: string;
      revenue: number;
      percentage: number;
    }>;
  };
  realtime: {
    todayRevenue: number;
    todayOrders: number;
    onlineUsers: number;
    recentOrders: any[];
  };
  loading: boolean;
  error: string | null;
  period: 'day' | 'week' | 'month' | 'quarter' | 'year';
  shopId?: string;
}

const initialState: SalesState = {
  overview: {
    totalRevenue: 0,
    totalOrders: 0,
    totalProducts: 0,
    totalCustomers: 0,
    averageOrderValue: 0,
    conversionRate: 0,
  },
  trends: {
    revenueData: [],
    categoryData: [],
  },
  realtime: {
    todayRevenue: 0,
    todayOrders: 0,
    onlineUsers: 0,
    recentOrders: [],
  },
  loading: false,
  error: null,
  period: 'month',
};

export const fetchSalesOverview = createAsyncThunk(
  'sales/fetchOverview',
  async (params: any, { rejectWithValue }) => {
    try {
      return {
        totalRevenue: 0,
        totalOrders: 0,
        totalProducts: 0,
        totalCustomers: 0,
        averageOrderValue: 0,
        conversionRate: 0,
      };
    } catch (error: any) {
      return rejectWithValue(error.message || '获取销售概览失败');
    }
  }
);

const salesSlice = createSlice({
  name: 'sales',
  initialState,
  reducers: {
    setPeriod: (state, action) => {
      state.period = action.payload;
    },
    setShopId: (state, action) => {
      state.shopId = action.payload;
    },
    updateRealtime: (state, action) => {
      state.realtime = { ...state.realtime, ...action.payload };
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchSalesOverview.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchSalesOverview.fulfilled, (state, action) => {
        state.loading = false;
        state.overview = action.payload;
      })
      .addCase(fetchSalesOverview.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { setPeriod, setShopId, updateRealtime, clearError } = salesSlice.actions;
export default salesSlice.reducer;
